package com.sogoodsoft.service.account;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
import com.sogoodsoft.entity.account.Authority;
import com.sogoodsoft.entity.account.Role;
import com.sogoodsoft.entity.account.SecurityUser;
import com.sogoodsoft.entity.account.User;
import com.sogoodsoft.service.app.OrganizationService;
import com.sogoodsoft.service.security.Identify;

import com.google.common.collect.Sets;

/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数.
 * 
 * @author calvin
 */
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {

	private AccountManager accountManager;
	
	@Autowired
	private OrganizationService orgService;
	private static Logger logger = LoggerFactory.getLogger(System.class); 
	/**
	 * 获取用户Details信息的回调函数.
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

		logger.debug("失败次数："+Identify.final_count);
		if((!Identify.valid)&&(!Identify.experience)){
			Identify.SN =  orgService.getRoot().getNote();
			Identify.getInstance().verify();
			while(Identify.busy){
			}
			if((Identify.final_count>Identify.final_limit)){
			throw new BadCredentialsException("对不起，该版本已过有效期，因无法再保证数据安全性而暂停使用！请及时与至好软件联系，由工作人员帮您处理！");
			}
		}
		
		User user = accountManager.findUserByLoginName(username);
		if (user == null) {
			throw new BadCredentialsException("用户名不存在！");
		}

		Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user);

		//-- infosys示例中无以下属性, 暂时全部设为true. --//
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		SecurityUser sUser  = new SecurityUser(user.getLoginName(), user
				.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);
		sUser.setUser(user);
		return sUser;
//		UserDetails userdetails = new org.springframework.security.core.userdetails.User(user.getLoginName(), user
//				.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);

//		return userdetails;
	}

	/**
	 * 获得用户所有角色的权限集合.
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities(User user) {
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		for (Role role : user.getRoleList()) {
			for (Authority authority : role.getAuthorityList()) {
				authSet.add(new GrantedAuthorityImpl(authority.getPrefixedName()));
			}
		}
		return authSet;
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}
}
